package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.startup.UserConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 菜品或套餐加入购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        // 判断菜品/套裁是否已存在
        Long userId = BaseContext.getCurrentId();
        Long dishId = shoppingCart.getDishId();

        LambdaQueryWrapper<ShoppingCart> cartWrapper = new LambdaQueryWrapper<>();
        cartWrapper.eq(ShoppingCart::getUserId, userId);
        if(dishId != null) {
            cartWrapper.eq(ShoppingCart::getDishId, dishId);
        } else if (shoppingCart.getSetmealId() != null) {
            cartWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart cart = shoppingCartService.getOne(cartWrapper);

        if(cart != null) {
            Integer number = cart.getNumber();
            number += 1;
            cart.setNumber(number);
            shoppingCartService.updateById(cart);

        } else {
            shoppingCart.setUserId(userId);
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);

            cart = shoppingCart;
        }
        return R.success(cart);
    }

    /**
     * 查询用户购物车中数据
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        List<ShoppingCart> shoppingCartList = shoppingCartService.shoppingList();
        return R.success(shoppingCartList);
    }

    @DeleteMapping("/clean")
    public R<String> clean() {
        shoppingCartService.clear();
        return R.success("清空购物车成功");
    }







}
